#include<iostream>
#include<string>
#include<unistd.h>
#include<cerrno>
#include<cstring>
#include<sys/wait.h>
#include<sys/types.h>

//fork之后子进程是能拿到父进程的数据的
using namespace std;
const int _size=1024;
//子进程读
void SubProcessRead(int rfd)
{
    char inbuffer[_size];
    ssize_t n=read(rfd,inbuffer,sizeof(inbuffer)-1);
    inbuffer[n]=0;//'\0'手动添加一个\0
    cout<<inbuffer<<endl;
}
//父进程写
void FatherProcessWrite(int wfd)
{
    string message="i am father!";
    write(wfd,message.c_str(),message.size());
    sleep(1);
}

int main()
{
    //1.创建管道
    int pipefd[2];
    int n=pipe(pipefd);//输出型参数
    if(n!=0)
    {
        cerr<<"errno:"<<errno<<"errstring:"<<strerror(errno)<<endl;
        return 1;
    }
    //pipefd[0]->0->r(读)
    //pipefd[1]->1->w(写)
    cout<<"pipefd[0]:"<<pipefd[0]<<" "<<"pipefd[1]:"<<pipefd[1]<<endl;
    sleep(1);

    //2.创建子进程
    //3.关闭不需要的文件描述符
    pid_t id=fork();
    if(id==0)
    {
        sleep(1);
        cout<<"子进程关闭不需要的fd,准备接收消息"<<endl;
        //子进程---read
        close(pipefd[1]);
        SubProcessRead(pipefd[0]);
        close(pipefd[0]);
        exit(0);
    }

    cout<<"父进程关闭不需要的fd,准备发消息"<<endl;
    sleep(1);
    //父进程---write
    close(pipefd[0]);
    FatherProcessWrite(pipefd[1]);
    close(pipefd[1]);
    pid_t rid=waitpid(id,nullptr,0);
    if(rid>0)
    {
        cout<<"wait child process done"<<endl;
    }
    return 0;
}